import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '../utils/storage';


Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'home',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import(/*webpackChunkName: "login" */'@/views/login/index.vue')
  },
  {
    path: '/layout',
    name: 'layout',
    component: () => import(/*webpackChunkName: "layout" */'@/views/layout/index.vue'),
    redirect: '/layout/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'dashboard',
        component: () => import('@/views/dashboard/index.vue')
      },
      {
        path: 'article',
        name: 'article',
        component: () => import('@/views/article/index.vue')
      }
    ]
  }

]


const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, resolve, reject) {
  if (resolve || reject) return originalPush.call(this, location, resolve, reject)
  return originalPush.call(this, location).catch((e) => { })
}

const router = new VueRouter({
  routes
})

// 白名单，定义成登录
const whiteList = ['/login']

// 路由导航守卫
router.beforeEach((to, from, next) => {
  // 1. 看有没有 token (vuex)，如果有，直接放行

  const token = getToken()
  if (token) {
    next()
    return
  }

  // 2. 看是否在 白名单，如果在，直接放行
  if (whiteList.includes(to.path)) {
    next()
    return
  }

  // 3. 其他情况，拦截到登录
  next('/login')
})
export default router
